package org.example.new_hbps_backend_reconstruction.controller.patient;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OSS文件管理控制器
 * 提供文件上传、下载、删除、移动等完整的OSS文件管理接口
 */
@Slf4j
@RestController
@RequestMapping("/api/oss")
@Tag(name = "OSS文件管理", description = "提供OSS文件存储相关接口")
public class OssController {

    @Autowired
    private OssService ossService;

    /**
     * 上传文件到指定路径
     */
    @PostMapping("/upload")
    @Operation(summary = "上传文件", description = "上传文件到OSS指定路径")
    public ResponseEntity<?> uploadFile(
            @Parameter(description = "上传的文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "存储路径") @RequestParam("path") String path,
            @Parameter(description = "重命名文件名（包含后缀）") @RequestParam("rename") String rename) {
        try {
            boolean result = ossService.uploadFile(file, path, rename);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "文件上传成功" : "文件上传失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("文件上传失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 上传文件到指定存储桶
     */
    @PostMapping("/upload-bucket")
    @Operation(summary = "上传文件到指定存储桶", description = "上传文件到指定的OSS存储桶")
    public ResponseEntity<?> uploadBucketFile(
            @Parameter(description = "上传的文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "存储桶名称") @RequestParam("bucketName") String bucketName,
            @Parameter(description = "对象名称（包含路径）") @RequestParam("objectName") String objectName) {
        try {
            boolean result = ossService.uploadBucketFile(file, bucketName, objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "文件上传成功" : "文件上传失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("文件上传失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 上传文件并返回访问URL
     */
    @PostMapping("/upload-with-url")
    @Operation(summary = "上传文件并返回URL", description = "上传文件到OSS并返回带签名的访问URL")
    public ResponseEntity<?> uploadFileAndGetUrl(
            @Parameter(description = "上传的文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "对象名称（包含路径）") @RequestParam("objectName") String objectName) {
        try {
            String url = ossService.uploadFileAndGetUrl(file, objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", url != null);
            response.put("url", url);
            response.put("message", url != null ? "文件上传成功" : "文件上传失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("文件上传并获取URL失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 根据URL上传文件到OSS
     */
    @PostMapping("/upload-from-url")
    @Operation(summary = "根据URL上传文件", description = "从指定URL下载文件并上传到OSS")
    public ResponseEntity<?> uploadFromUrl(
            @Parameter(description = "文件URL") @RequestParam("fileUrl") String fileUrl,
            @Parameter(description = "对象名称（包含路径）") @RequestParam("objectName") String objectName) {
        try {
            boolean result = ossService.uploadUrl(fileUrl, objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "文件上传成功" : "文件上传失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据URL上传文件失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取文件访问URL
     */
    @GetMapping("/url")
    @Operation(summary = "获取文件URL", description = "获取OSS文件的访问URL")
    public ResponseEntity<?> getFileUrl(
            @Parameter(description = "对象名称") @RequestParam("objectName") String objectName) {
        try {
            String url = ossService.getFileUrl(objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", url != null);
            response.put("url", url);
            response.put("message", url != null ? "获取URL成功" : "文件不存在或获取失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取文件URL失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取文件URL失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取指定存储桶中的文件URL
     */
    @GetMapping("/bucket-url")
    @Operation(summary = "获取指定存储桶文件URL", description = "获取指定存储桶中文件的访问URL")
    public ResponseEntity<?> getBucketFileUrl(
            @Parameter(description = "存储桶名称") @RequestParam("bucketName") String bucketName,
            @Parameter(description = "对象名称") @RequestParam("objectName") String objectName) {
        try {
            String url = ossService.getBucketFileUrl(bucketName, objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", url != null);
            response.put("url", url);
            response.put("message", url != null ? "获取URL成功" : "文件不存在或获取失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取存储桶文件URL失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取文件URL失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取图片URL（支持多种格式）
     */
    @GetMapping("/image-url")
    @Operation(summary = "获取图片URL", description = "获取图片的访问URL，支持jpg、jpeg、png、svg格式")
    public ResponseEntity<?> getImageUrl(
            @Parameter(description = "存储桶名称") @RequestParam("bucketName") String bucketName,
            @Parameter(description = "图片基础名称（不包含后缀）") @RequestParam("objectBaseName") String objectBaseName) {
        try {
            String url = ossService.getImageUrl(bucketName, objectBaseName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", url != null);
            response.put("url", url);
            response.put("message", url != null ? "获取图片URL成功" : "图片不存在");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取图片URL失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取图片URL失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 创建目录
     */
    @PostMapping("/directory")
    @Operation(summary = "创建目录", description = "在OSS中创建新目录")
    public ResponseEntity<?> createDirectory(
            @Parameter(description = "目录名称") @RequestParam("directory") String directory,
            @Parameter(description = "目标路径") @RequestParam("path") String path) {
        try {
            boolean result = ossService.createDirectory(directory, path);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "目录创建成功" : "目录创建失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建目录失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "目录创建失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 列出文件
     */
    @GetMapping("/list")
    @Operation(summary = "列出文件", description = "根据前缀列出OSS中的文件和目录")
    public ResponseEntity<?> listFiles(
            @Parameter(description = "文件前缀") @RequestParam("prefix") String prefix) {
        try {
            List<String> files = ossService.listFiles(prefix);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("files", files);
            response.put("count", files.size());
            response.put("message", "文件列表获取成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("列出文件失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "列出文件失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除文件（通过完整路径）
     */
    @DeleteMapping("/file")
    @Operation(summary = "删除文件", description = "删除指定完整路径的文件")
    public ResponseEntity<?> deleteFileByPath(
            @Parameter(description = "文件完整路径") @RequestParam("pathName") String pathName) {
        try {
            boolean result = ossService.deleteFile(pathName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "文件删除成功" : "文件删除失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除文件失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件删除失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }


    /**
     * 删除指定存储桶中的文件
     */
    @DeleteMapping("/bucket-file")
    @Operation(summary = "删除存储桶文件", description = "删除指定存储桶中的文件")
    public ResponseEntity<?> deleteBucketFile(
            @Parameter(description = "存储桶名称") @RequestParam("bucketName") String bucketName,
            @Parameter(description = "文件路径") @RequestParam("path") String path,
            @Parameter(description = "文件名") @RequestParam("fileName") String fileName) {
        try {
            boolean result = ossService.deleteBucketFile(bucketName, path, fileName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "文件删除成功" : "文件删除失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除存储桶文件失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件删除失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除目录
     */
    @DeleteMapping("/directory")
    @Operation(summary = "删除目录", description = "删除OSS中的指定目录及其所有内容")
    public ResponseEntity<?> deleteDirectory(
            @Parameter(description = "目录路径") @RequestParam("directory") String directory) {
        try {
            boolean result = ossService.deleteDirectory(directory);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "目录删除成功" : "目录删除失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除目录失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "目录删除失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 移动文件
     */
    @PutMapping("/move-file")
    @Operation(summary = "移动文件", description = "将文件从一个位置移动到另一个位置")
    public ResponseEntity<?> moveFile(
            @Parameter(description = "文件名") @RequestParam("filename") String filename,
            @Parameter(description = "原路径") @RequestParam("ori_path") String ori_path,
            @Parameter(description = "目标路径") @RequestParam("tar_path") String tar_path) {
        try {
            boolean result = ossService.moveFile(filename, ori_path, tar_path);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "文件移动成功" : "文件移动失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("移动文件失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件移动失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 移动目录
     */
    @PutMapping("/move-directory")
    @Operation(summary = "移动目录", description = "将目录及其所有内容从一个位置移动到另一个位置")
    public ResponseEntity<?> moveDirectory(
            @Parameter(description = "原路径") @RequestParam("ori_path") String ori_path,
            @Parameter(description = "目标路径") @RequestParam("tar_path") String tar_path) {
        try {
            boolean result = ossService.moveDirectory(ori_path, tar_path);
            Map<String, Object> response = new HashMap<>();
            response.put("success", result);
            response.put("message", result ? "目录移动成功" : "目录移动失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("移动目录失败: ", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "目录移动失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
